<template>
  <div class="dashboard-container agri-page-container">
    <!-- 顶部欢迎区和摘要信息 -->
    <div class="welcome-section agri-page-header">
      <div class="agri-page-title">
        <h2>欢迎使用智慧农业信息系统, {{ userStore.userName }}</h2>
      </div>
      <div>
        <p class="welcome-subtitle">今天是 {{ currentDate }}，{{ weatherInfo }}</p>
      </div>
    </div>
    
    <!-- 主要内容区域 -->
    <div class="dashboard-layout">
      <!-- 左侧主要区域 -->
      <div class="main-content">
        <!-- 买家视图：产品推荐区 -->
        <div v-if="userStore.isBuyer" class="section-container">
          <div class="section-header">
            <div class="section-title">
              <el-icon><ShoppingBag /></el-icon>
              <span>推荐农产品</span>
          </div>
            <el-button type="primary" size="small" plain @click="navigateTo('/main/buyer/farmers')">查看更多</el-button>
          </div>
          
          <div class="section-content product-grid" v-loading="loading.products">
            <div v-if="!recommendedProducts || recommendedProducts.length === 0" class="empty-section">
              <el-empty description="暂无推荐产品" />
          </div>
            <div v-else class="product-items">
              <div 
                v-for="product in recommendedProducts" 
                :key="product.id" 
                class="product-item"
                @click="viewProductDetail(product.id)"
              >
                <div class="product-image">
                  <el-image :src="formatImageUrl(product.image)" fit="cover" />
                  <div class="product-category" v-if="product.category">{{ product.category }}</div>
                    </div>
                <div class="product-details">
                  <h4 class="product-name">{{ product.name }}</h4>
                  <div class="product-farm">{{ product.farmerName || '未知农户' }}</div>
                  <div class="product-rating">
                    <el-rate :model-value="product.farmerRating || 5" disabled text-color="#ff9900" />
                  </div>
                  <div class="product-price">
                    <span class="price-value">¥{{ product.price }}</span>
                    <span class="price-unit">/ {{ product.unit }}</span>
              </div>
                    </div>
                  </div>
              </div>
                    </div>
                  </div>
        
        <!-- 农户视图：种植状态 -->
        <div v-if="userStore.isFarmer" class="section-container">
          <div class="section-header">
            <div class="section-title">
                <el-icon><House /></el-icon>
              <span>种植状态</span>
              </div>
            <el-button type="primary" size="small" plain @click="navigateTo('/main/farmer/planting')">查看全部</el-button>
            </div>
          
          <div class="section-content" v-loading="loading.plantings">
            <div v-if="plantings.length === 0" class="empty-section">
            <el-empty description="暂无种植记录" />
              </div>
            <div v-else class="planting-items">
              <div class="planting-card" v-for="planting in plantings" :key="planting.id">
                <div class="planting-card-header">
                  <div class="planting-avatar">
                    <el-avatar :size="50" :icon="getCropIcon(planting.cropType || planting.category)" class="crop-avatar"></el-avatar>
                  </div>
                  <div class="planting-title">
                    <h3>{{ planting.cropName || planting.name || '未命名作物' }}</h3>
                    <el-tag size="small" :type="getStatusType(planting.status)" effect="dark">
                      {{ planting.statusName || getPlantingStatusText(planting.status) }}
                      </el-tag>
                    </div>
                  </div>
                
                <div class="planting-card-body">
                  <!-- 生长进度条 -->
                  <div class="growth-progress-simple">
                    <div class="progress-header">
                      <span class="progress-title">生长进度</span>
                      <span class="progress-percentage">{{ calculateGrowthProgress(planting) }}%</span>
              </div>
                    <el-progress 
                      :percentage="calculateGrowthProgress(planting)" 
                      :status="getProgressStatus(planting)"
                      :stroke-width="10"
                      :show-text="false"
                      class="custom-progress"
                    ></el-progress>
                    </div>
                  
                  <!-- 简化的信息表格 -->
                  <div class="planting-info-table">
                    <div class="info-row">
                      <div class="info-cell">
                        <el-icon><Location /></el-icon>
                        <span class="info-label">地块：</span>
                  </div>
                      <div class="info-value-cell">{{ planting.landName || planting.land || '未指定地块' }}</div>
                    </div>
                    
                    <div class="info-row">
                      <div class="info-cell">
                        <el-icon><Calendar /></el-icon>
                        <span class="info-label">种植日期：</span>
              </div>
                      <div class="info-value-cell">{{ formatDate(planting.plantingDate) }}</div>
                    </div>
                    
                    <div class="info-row">
                      <div class="info-cell">
                        <el-icon><Timer /></el-icon>
                        <span class="info-label">预计收获：</span>
                  </div>
                      <div class="info-value-cell">{{ formatDate(planting.expectedHarvestDate) }}</div>
                    </div>
                    
                    <div class="info-row">
                      <div class="info-cell">
                        <el-icon><Odometer /></el-icon>
                        <span class="info-label">预计产量：</span>
              </div>
                      <div class="info-value-cell">{{ planting.expectedYield || planting.yield || 0 }}{{ planting.unit || 'kg' }}</div>
            </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

      
        <!-- 卖家视图：最近订单 -->
        <div v-if="userStore.isSeller" class="section-container compact-card">
          <div class="section-header">
            <div class="section-title">
              <el-icon><ShoppingCart /></el-icon>
              <span>最近订单</span>
          </div>
            <el-button type="primary" size="small" plain @click="navigateTo('/main/seller/seller-orders')">所有订单</el-button>
                      </div>
          
          <div class="section-content" v-loading="loading.orders">
            <div v-if="!recentOrders || recentOrders.length === 0" class="empty-section">
              <el-empty description="暂无订单数据" />
                    </div>
            
            <el-table v-else :data="recentOrders" style="width: 100%" stripe :max-height="200">
              <el-table-column prop="orderNumber" label="订单编号" min-width="120" />
              <el-table-column prop="buyerName" label="买家" min-width="100" />
              <el-table-column prop="productName" label="商品" min-width="120" />
              <el-table-column label="金额" min-width="100">
                <template #default="scope">
                  <span class="price-text">¥{{ scope.row.totalAmount }}</span>
          </template>
              </el-table-column>
              <el-table-column label="状态" min-width="100">
                <template #default="scope">
                  <el-tag :type="getOrderStatusType(scope.row.status)" size="small">
                    {{ getOrderStatusText(scope.row.status) }}
                    </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button type="primary" size="small" text @click="handleViewOrder(scope.row)">
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
                  </div>
                  
        <!-- 卖家视图：库存管理 -->
        <div v-if="userStore.isSeller" class="section-container compact-card">
          <div class="section-header">
            <div class="section-title">
              <el-icon><Goods /></el-icon>
              <span>库存管理</span>
          </div>
            <el-button type="primary" size="small" plain @click="navigateTo('/main/seller/products')">管理商品</el-button>
          </div>
          
          <div class="section-content" v-loading="loading.inventory">
            <div v-if="!lowStockProducts || lowStockProducts.length === 0" class="empty-section">
              <el-empty description="无需补货的商品" />
                    </div>
            
            <div v-else class="low-stock-alert">
              <el-alert
                title="库存预警"
                type="warning"
                description="以下商品库存不足"
                show-icon
                :closable="false"
                style="margin-bottom: 6px;"
              />
              
              <div class="low-stock-products">
                <div class="low-stock-item" v-for="product in lowStockProducts" :key="product.id">
                  <div class="product-info">
                    <div class="product-thumb">
                      <el-image :src="formatImageUrl(product.image)" fit="cover" />
                    </div>
                    <div class="product-details">
                      <div class="product-name">{{ product.name }}</div>
                      <div class="product-price">¥{{ product.price }} / {{ product.unit }}</div>
                    </div>
                    </div>
                  <div class="stock-info">
                    <el-progress
                      :percentage="getStockPercentage(product.stock, product.safeStock)"
                      :status="product.stock < product.safeStock ? 'exception' : 'success'"
                      :stroke-width="4"
                    />
                    <div class="stock-text">
                      <div class="current-stock">当前: {{ product.stock }} {{ product.unit }}</div>
                  </div>
                    </div>
                  <el-button type="warning" size="small" text @click="handleRefillStock(product.id)">
                    补充
                  </el-button>
                  </div>
          </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧边栏 -->
      <div class="sidebar-content">
        <!-- 消息通知模块 -->
        <div class="widget-container">
          <div class="widget-header">
            <div class="widget-title">
                <el-icon><Bell /></el-icon>
              <span>消息通知</span>
              </div>
            <el-button link @click="navigateTo('/main/notifications')">查看全部</el-button>
            </div>
          
          <div class="widget-content">
            <div v-if="notifications.length === 0" class="empty-widget">
              <el-empty description="暂无消息通知" :image-size="60" />
          </div>
            <div v-else class="notification-items">
            <div 
                v-for="notification in notifications.slice(0, 3)" 
              :key="notification.id" 
              class="notification-item"
                :class="{ 'unread': !notification.isRead }"
                @click="handleNotificationClick(notification)"
            >
                <div class="notification-type" :class="notification.type">
                <el-icon>
                  <component :is="getNotificationIcon(notification.type)" />
                </el-icon>
              </div>
                <div class="notification-details">
                  <div class="notification-header">
                    <span class="notification-title">{{ notification.title }}</span>
                    <span class="notification-time">{{ formatNotificationTime(notification.time || notification.createTime) }}</span>
              </div>
                  <p class="notification-content">{{ notification.content }}</p>
            </div>
          </div>
            </div>
          </div>
        </div>
        
        <!-- 快捷操作模块 -->
        <div class="widget-container">
          <div class="widget-header">
            <div class="widget-title">
                <el-icon><Link /></el-icon>
              <span>快捷操作</span>
              </div>
            </div>
          
          <div class="widget-content">
            <div class="shortcut-items">
            <div 
                v-for="shortcut in shortcuts.slice(0, 6)" 
              :key="shortcut.title"
              class="shortcut-item"
              @click="navigateTo(shortcut.route)"
            >
              <div class="shortcut-icon" :style="{ backgroundColor: shortcut.bgColor }">
                <el-icon>
                  <component :is="shortcut.icon" />
                </el-icon>
              </div>
                <span class="shortcut-name">{{ shortcut.title }}</span>
            </div>
          </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore, useFarmerStore, useAppStore, useBuyerStore, useSellerStore } from '../../store';
import {
  Calendar,
  Bell,
  Sunny,
  Cloudy,
  Lightning,
  Moon,
  ArrowUp,
  ArrowDown,
  Upload,
  TrendCharts,
  ShoppingCart,
  Goods,
  Message,
  Warning,
  CircleCheck,
  Timer,
  Crop,
  Link,
  House,
  Money,
  Document,
  Location,
  Plus,
  Download,
  Setting,
  Management,
  Shop,
  List,
  Box,
  User,
  ShoppingBag,
  OfficeBuilding,
  CaretTop,
  CaretBottom,
  Star,
  UserFilled,
  Odometer
} from '@element-plus/icons-vue';

// 路由和状态管理
const router = useRouter();
const userStore = useUserStore();
const farmerStore = useFarmerStore();
const appStore = useAppStore();
const buyerStore = useBuyerStore();
const sellerStore = useSellerStore();
const route = useRoute();
const defaultProductImage = '/placeholder.png';

// 计算属性
const activeMenu = computed(() => route.path);
const userInfo = computed(() => userStore.userInfo);

// 当前日期
const currentDate = computed(() => {
  const date = new Date();
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
});

// 天气信息
const weatherInfo = ref('晴朗 26°C');

// 图表周期选择
const salesChartPeriod = ref('month');

// 模拟卖家统计数据
const sellerStats = computed(() => {
  if (userStore.isSeller) {
    return [
      {
        title: '销售总额',
        value: '￥38,000',
        icon: 'TrendCharts',
        bgColor: '#409EFF',
        trend: { type: 'up', value: 18 }
      },
      {
        title: '订单数量',
        value: '45单',
        icon: 'ShoppingCart',
        bgColor: '#67C23A',
        trend: { type: 'up', value: 22 }
      },
      {
        title: '商品数量',
        value: '12件',
        icon: 'Goods',
        bgColor: '#E6A23C',
        trend: { type: 'down', value: 5 }
      },
      {
        title: '客户数量',
        value: '28位',
        icon: 'User',
        bgColor: '#F56C6C',
        trend: { type: 'up', value: 12 }
      }
    ];
  }
  return [];
});

// 模拟最近订单数据
const recentOrders = ref([]);

// 模拟库存不足的商品
const lowStockProducts = ref([]);

// 模拟客户统计数据
const customerStats = ref({
  total: 28,
  new: 5,
  repurchaseRate: '68%'
});

// 施肥提醒任务
const fertilizingTasks = ref([
  {
    id: 1,
    title: '东区水稻田施肥',
    content: '水稻田需要补充复合肥，建议用量15-20kg/亩',
    date: '2023-06-01',
    status: 'red'
  },
  {
    id: 2,
    title: '西区蔬菜地施肥',
    content: '白菜需要补充有机肥，建议用量50kg/亩',
    date: '2023-06-03',
    status: 'yellow'
  },
  {
    id: 3,
    title: '南区果树园施肥',
    content: '苹果园需要补充有机肥，建议用量60kg/亩',
    date: '2023-06-10',
    status: 'green'
  }
]);

// 收获提醒任务
const harvestTasks = ref([
  {
    id: 1,
    title: '西区白菜收获',
    content: '预计可收获有机白菜7500kg',
    date: '2023-07-15',
    days: 45
  },
  {
    id: 2,
    title: '东区水稻收获',
    content: '预计可收获优质稻米5000kg',
    date: '2023-08-20',
    days: 81
  }
]);

// 订单提醒任务
const orderTasks = computed(() => {
  if (userStore.isFarmer) {
    return [
  {
    id: 1,
    title: '有机白菜订单',
    content: '杭州果品有限公司订购有机白菜300kg',
    date: '2023-06-05',
    priority: 'medium',
    type: 'sale'
  },
  {
    id: 2,
    title: '复合肥订单',
    content: '需要从武汉肥料有限公司购买复合肥200kg',
    date: '2023-06-02',
    priority: 'high',
    type: 'purchase'
  }
    ];
  }

  if (userStore.isBuyer) {
    return [
  {
    id: 1,
        title: '待付款订单',
        content: '您有3个订单等待付款，请及时处理',
        date: '2023-06-01',
        priority: 'high',
        type: 'purchase'
  },
  {
    id: 2,
        title: '待收货订单',
        content: '您有2个订单已发货，请注意查收',
        date: '2023-06-03',
        priority: 'medium',
        type: 'purchase'
  },
  {
    id: 3,
        title: '订单评价提醒',
        content: '您有5个已完成订单未评价，请及时评价',
        date: '2023-06-05',
        priority: 'low',
        type: 'purchase'
      },
      {
        id: 4,
        title: '新品推荐',
        content: '您关注的农户青山果园上新了时令水果',
        date: '2023-06-06',
        priority: 'medium',
        type: 'info'
      }
    ];
  }
  
  if (userStore.isSeller) {
    return [
      {
        id: 1,
        title: '待发货订单',
        content: '有5个新订单等待发货处理',
        date: '2023-06-01',
        priority: 'high',
        type: 'sale'
      },
      {
        id: 2,
        title: '退款申请',
        content: '有2个订单申请退款，请及时处理',
        date: '2023-06-02',
        priority: 'high',
        type: 'sale'
      }
    ];
  }
  
  return [];
});

// 在script部分添加loading状态以及替换recommendedProducts的实现
const loading = ref({
  products: false,
  orders: false,
  transactions: false,
  plantings: false,
  salesChart: false,
  inventory: false,
  customers: false
});

// 在script部分替换推荐产品的实现方式
const recommendedProducts = ref([]);
const recentTransactions = ref([]);

// 种植记录
const plantings = ref([]);

// 消息通知
const notifications = ref([
  {
    id: 1,
    title: '施肥超期提醒',
    content: '东区水稻田施肥已超期3天，请尽快处理',
    time: '10分钟前',
    type: 'warning',
    read: false
  },
  {
    id: 2,
    title: '订单通知',
    content: '杭州果品有限公司已确认订单，请注意发货时间',
    time: '1小时前',
    type: 'order',
    read: false
  },
  {
    id: 3,
    title: '系统公告',
    content: '系统将于今晚22:00-23:00进行维护升级',
    time: '昨天',
    type: 'system',
    read: true
  },
  {
    id: 4,
    title: '价格行情',
    content: '本周大白菜市场价格上涨12%，出售正当时',
    time: '2天前',
    type: 'price',
    read: true
  }
]);

// 天气数据
const weather = ref({
  current: {
    temp: 26,
    desc: '晴朗',
    type: 'sunny',
    humidity: 65,
    wind: 12,
    pressure: 1013
  },
  forecast: [
    { day: '周一', high: 28, low: 19, type: 'sunny' },
    { day: '周二', high: 26, low: 18, type: 'cloudy' },
    { day: '周三', high: 25, low: 20, type: 'rainy' },
    { day: '周四', high: 27, low: 21, type: 'sunny' },
    { day: '周五', high: 29, low: 22, type: 'sunny' }
  ]
});

// 快捷操作按钮
const shortcuts = computed(() => {
  // 农户快捷操作
  if (userStore.isFarmer) {
    return [
      { title: '添加种植', icon: 'Plus', route: '/main/farmer/planting', bgColor: '#67C23A' },
      { title: '施肥记录', icon: 'Document', route: '/main/farmer/fertilizer', bgColor: '#409EFF' },
      { title: '库存管理', icon: 'Box', route: '/main/farmer/inventory', bgColor: '#E6A23C' },
      { title: '土地管理', icon: 'Location', route: '/main/farmer/land', bgColor: '#F56C6C' },
      { title: '数据导出', icon: 'Download', route: '/main/farmer/export', bgColor: '#909399' },
      { title: '系统设置', icon: 'Setting', route: '/main/profile', bgColor: '#6B778C' }
    ];
  }
  
  // 买家快捷操作
  if (userStore.isBuyer) {
    return [
      { title: '浏览产品', icon: 'ShoppingBag', route: '/main/buyer/farmers', bgColor: '#67C23A' },
      { title: '我的订单', icon: 'List', route: '/main/buyer/orders', bgColor: '#409EFF' },
      { title: '提交投诉', icon: 'Warning', route: '/main/buyer/complaints', bgColor: '#F56C6C' },
      { title: '创建订单', icon: 'Plus', route: '/main/buyer/farmers', bgColor: '#E6A23C' },
      { title: '农户列表', icon: 'User', route: '/main/buyer/farmers', bgColor: '#909399' },
      { title: '个人设置', icon: 'Setting', route: '/main/profile', bgColor: '#6B778C' }
    ];
  }
  
  // 卖家快捷操作
  if (userStore.isSeller) {
    return [
      { title: '商品管理', icon: 'Goods', route: '/main/seller/products', bgColor: '#67C23A' },
      { title: '订单处理', icon: 'List', route: '/main/seller/seller-orders', bgColor: '#409EFF' },
      { title: '添加商品', icon: 'Plus', route: '/main/seller/products', bgColor: '#E6A23C' }
    ];
  }
  
  return [];
});

// 获取通知图标
function getNotificationIcon(type) {
  switch (type) {
    case 'success':
      return CircleCheck;
    case 'warning':
      return Warning;
    case 'info':
      return Message;
    default:
      return Bell;
  }
}

// 获取天气图标
function getWeatherIcon(type) {
  switch (type) {
    case 'sunny':
      return Sunny;
    case 'cloudy':
      return Cloudy;
    case 'thunder':
      return Lightning;
    case 'night':
      return Moon;
    default:
      return Sunny;
  }
}

// 导航到指定路由
function navigateTo(route) {
  router.push(route);
}

// 查看产品详情
function viewProductDetail(productId) {
  // 模拟导航到产品详情页
  console.log('查看产品详情:', productId);
  // router.push(`/main/buyer/product/${productId}`);
  // 暂时使用跳转到农户列表页
  router.push('/main/buyer/farmers');
}

// 格式化图片URL
const formatImageUrl = (url) => {
  if (!url) return defaultProductImage;
  
  // 如果是相对URL，添加API前缀
  if (url.startsWith('/file/') || url.startsWith('/api/file/')) {
    const token = localStorage.getItem('token');
    const apiUrl = url.startsWith('/api') ? url : `/api${url}`;
    
    if (token) {
      return `${apiUrl}?token=${encodeURIComponent(token)}`;
    }
    return apiUrl;
  }
  
  return url;
};

// 格式化交易日期
function formatTransactionDate(dateString) {
  if (!dateString) return '';
  
  try {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误', error);
    return dateString;
  }
}

// 组件挂载时
onMounted(async () => {
  // 加载通知数据
  try {
    await appStore.fetchNotifications();
    notifications.value = appStore.notifications;
  } catch (error) {
    console.error('加载通知失败:', error);
  }
  
  // 根据用户角色加载特定数据
    if (userStore.isFarmer) {
    // 加载农户特定数据
    try {
      // 加载种植记录
      loading.value.plantings = true;
      await farmerStore.fetchLands(); // 先获取土地信息，以便关联种植记录
      const plantingsData = await farmerStore.fetchPlantings();
      
      if (plantingsData && plantingsData.length > 0) {
        console.log('仪表盘获取到的种植记录:', plantingsData.length, '条');
        console.log('种植记录第一条数据示例:', JSON.stringify(plantingsData[0]));
        
        // 处理种植记录数据
        const processedPlantings = plantingsData.map(p => {
          // 确保重要字段都有值
          return {
            ...p,
            // 使用与种植管理界面一致的状态判断
            status: p.status === 0 || p.status === '0' ? 0 : (p.status || 1),
            statusName: p.statusName || (p.status === 0 || p.status === '0' ? '生长中' : '已收获'),
            // 尝试多种可能的字段名
            expectedHarvestDate: p.expectedHarvestDate || p.harvestDate || p.expectedHarvestTime,
            plantingDate: p.plantingDate || p.plantTime || p.createTime
          };
        });
        
        plantings.value = processedPlantings.slice(0, 3); // 只显示最近3条
        console.log('处理后的种植记录:', JSON.stringify(plantings.value));
      } else {
        console.warn('未获取到种植记录或记录为空');
        plantings.value = [];
    }
  } catch (error) {
      console.error('加载农户数据失败:', error);
    } finally {
      loading.value.plantings = false;
    }
  } 
  else if (userStore.isBuyer) {
    // 加载买家特定数据
    try {
      // 获取订单数据
      loading.value.orders = true;
      await buyerStore.fetchOrders();
      loading.value.orders = false;
      
      // 获取推荐产品（真实数据）
      loading.value.products = true;
      
      // 调用 store 方法获取产品
      await buyerStore.fetchAllProducts();
      
      // 从 store 中获取产品并设置推荐产品
      if (buyerStore.products && buyerStore.products.length > 0) {
        console.log('仪表盘获取到的产品数据:', buyerStore.products.length, '条');
        recommendedProducts.value = buyerStore.products.slice(0, 6);
        console.log('仪表盘推荐产品:', recommendedProducts.value.length, '条');
      } else {
        console.warn('未获取到产品数据或数据为空');
        recommendedProducts.value = [];
      }
      
      loading.value.products = false;
      
      // 获取交易记录
      loading.value.transactions = true;
      try {
        console.log('开始获取买家交易记录...');
        const transactions = await buyerStore.fetchTransactions();
        console.log('获取到的交易记录原始数据:', transactions);
        
        if (transactions && transactions.length > 0) {
          console.log('仪表盘获取到的交易记录:', transactions.length, '条');
          console.log('交易记录第一条数据示例:', transactions[0]);
          
          // 按交易日期排序（最新的排在前面）
          const sortedTransactions = [...transactions].sort((a, b) => {
            return new Date(b.transactionDate) - new Date(a.transactionDate);
          });
          
          recentTransactions.value = sortedTransactions.slice(0, 5); // 只显示最近5条
          console.log('处理后显示的交易记录:', recentTransactions.value);
        } else {
          console.warn('未获取到交易记录或记录为空');
          if (transactions) {
            console.warn('交易记录数组存在但长度为0');
          } else {
            console.warn('交易记录数组为null或undefined');
          }
          recentTransactions.value = [];
        }
      } catch (txError) {
        console.error('获取交易记录失败:', txError);
        if (txError.response) {
          console.error('错误响应数据:', txError.response.data);
          console.error('错误状态码:', txError.response.status);
        }
        recentTransactions.value = [];
      } finally {
        loading.value.transactions = false;
      }
      
    } catch (error) {
      console.error('加载买家数据失败:', error);
      loading.value.orders = false;
      loading.value.products = false;
      loading.value.transactions = false;
    }
  }
  else if (userStore.isSeller) {
    // 加载卖家特定数据
    try {
      // 获取卖家订单数据
      loading.value.orders = true;
      const ordersData = await sellerStore.fetchOrders();
      if (ordersData && ordersData.length > 0) {
        console.log('仪表盘获取到的订单数据:', ordersData.length, '条');
        // 按订单时间排序（最新的排在前面）
        const sortedOrders = [...ordersData].sort((a, b) => {
          return new Date(b.orderTime || b.createTime) - new Date(a.orderTime || a.createTime);
        });
        recentOrders.value = sortedOrders.slice(0, 2); // 只显示最近2条
      } else {
        console.warn('未获取到订单数据或数据为空');
        recentOrders.value = [];
      }
      loading.value.orders = false;
      
      // 获取库存商品数据
      loading.value.inventory = true;
      const productsData = await sellerStore.fetchProducts();
      if (productsData && productsData.length > 0) {
        console.log('仪表盘获取到的商品数据:', productsData.length, '条');
        // 筛选库存不足的商品（库存低于安全库存或库存低于10）
        lowStockProducts.value = productsData.filter(product => {
          const currentStock = Number(product.stock) || 0;
          const safeStock = Number(product.safeStock) || 20;
          return currentStock < safeStock;
        }).slice(0, 2); // 最多显示2个低库存商品
      } else {
        console.warn('未获取到商品数据或数据为空');
        lowStockProducts.value = [];
      }
      loading.value.inventory = false;
    } catch (error) {
      console.error('加载卖家数据失败:', error);
      loading.value.orders = false;
      loading.value.inventory = false;
    }
  }
});

// 添加格式化日期的方法
function formatDate(dateString) {
  // 先打印日期字段的原始值，方便调试
  console.log('日期字段原始值:', dateString);
  
  if (!dateString) {
    console.log('日期字段为空，尝试使用回退机制');
    return '未设置';
  }
  
  try {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  } catch (error) {
    console.error('日期格式化错误', error);
    return dateString;
  }
}

// 添加计算生长进度的方法
function calculateGrowthProgress(planting) {
  console.log('计算生长进度的输入数据:', JSON.stringify({
    id: planting.id,
    plantingDate: planting.plantingDate,
    expectedHarvestDate: planting.expectedHarvestDate
  }));
  
  if (!planting.plantingDate || !planting.expectedHarvestDate) {
    console.warn('缺少计算进度的必要字段:', planting.id);
    return 0;
  }
  
  try {
    const plantingDate = new Date(planting.plantingDate);
    const harvestDate = new Date(planting.expectedHarvestDate);
    const today = new Date();
    
    // 验证日期是否有效
    if (isNaN(plantingDate.getTime()) || isNaN(harvestDate.getTime())) {
      console.warn('日期格式无效:', {
        plantingDate: planting.plantingDate,
        harvestDate: planting.expectedHarvestDate
      });
      return 0;
    }
    
    // 如果已经超过预计收获日期
    if (today > harvestDate) return 100;
    
    // 计算总生长天数
    const totalDays = (harvestDate - plantingDate) / (1000 * 60 * 60 * 24);
    // 计算已经生长的天数
    const grownDays = (today - plantingDate) / (1000 * 60 * 60 * 24);
    
    // 计算进度百分比
    const progress = Math.round((grownDays / totalDays) * 100);
    const result = Math.min(Math.max(progress, 0), 100); // 确保在0-100之间
    
    console.log('计算出的生长进度:', result, '%');
    return result;
  } catch (error) {
    console.error('计算生长进度错误', error);
    return 0;
  }
}

// 获取进度状态
function getProgressStatus(planting) {
  const progress = calculateGrowthProgress(planting);
  if (progress >= 90) return 'success';
  if (progress >= 60) return 'warning';
  return '';
}

// 获取种植状态文本
function getPlantingStatusText(status) {
  // 与种植管理界面保持一致
  if (status === 0 || status === '0') {
    return '生长中';
  }
  
  const statusMap = {
    0: '生长中',
    1: '已收获',
    2: '已失败',
    3: '计划中'
  };
  return statusMap[status] || '未知状态';
}

// 获取作物图标
function getCropIcon(cropType) {
  if (!cropType) return 'Crop';
  
  const typeMap = {
    '水稻': 'Rice',
    '小麦': 'Wheat',
    '玉米': 'Corn',
    '蔬菜': 'Vegetable',
    '水果': 'Apple',
    '豆类': 'Bean'
  };
  
  return typeMap[cropType] || 'Crop';
}

// 处理通知点击
function handleNotificationClick(notification) {
  // 如果有路由信息，跳转到对应页面
  if (notification.actionRoute) {
    navigateTo(notification.actionRoute);
  }
}

// 格式化通知时间
function formatNotificationTime(timeString) {
  if (!timeString) return '';
  
  try {
    const date = new Date(timeString);
    const now = new Date();
    const diffMs = now - date;
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);
    
    if (diffSec < 60) return '刚刚';
    if (diffMin < 60) return `${diffMin}分钟前`;
    if (diffHour < 24) return `${diffHour}小时前`;
    if (diffDay < 30) return `${diffDay}天前`;
    
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  } catch (error) {
    console.error('时间格式化错误', error);
    return timeString;
  }
}

// 获取状态类型
function getStatusType(status) {
  // 与种植管理界面保持一致
  if (status === 0 || status === '0') {
    return 'success';
  }
  
  const statusMap = {
    0: 'success',
    1: 'info',
    2: 'danger',
    3: 'warning'
  };
  return statusMap[status] || 'info';
}

// 获取订单状态类型
function getOrderStatusType(status) {
  // 处理数字状态码
  if (typeof status === 'number' || !isNaN(parseInt(status))) {
    const statusNum = parseInt(status);
    switch (statusNum) {
      case 0: return 'warning'; // 待付款
      case 1: return 'info';    // 待发货
      case 2: return 'primary'; // 已发货
      case 3: return 'success'; // 已完成
      case 4: return 'danger';  // 已取消
      default: return 'info';
    }
  }

  // 处理字符串状态
  if (status === '待付款') return 'warning';
  if (status === '待发货') return 'info';
  if (status === '已发货') return 'primary';
  if (status === '已完成') return 'success';
  if (status === '已取消') return 'danger';
  return 'info';
}

// 获取订单状态文本
function getOrderStatusText(status) {
  // 处理数字状态码
  if (typeof status === 'number' || !isNaN(parseInt(status))) {
    const statusNum = parseInt(status);
    switch (statusNum) {
      case 0: return '待付款';
      case 1: return '待发货';
      case 2: return '已发货';
      case 3: return '已完成';
      case 4: return '已取消';
      default: return `状态${status}`;
    }
  }

  // 处理字符串状态
  const statusMap = {
    '待付款': '待付款',
    '待发货': '待发货',
    '已发货': '已发货',
    '已完成': '已完成',
    '已取消': '已取消'
  };
  return statusMap[status] || status;
}

// 获取库存百分比
function getStockPercentage(currentStock, safeStock) {
  if (currentStock <= 0 || safeStock <= 0) return 0;
  return Math.round((currentStock / safeStock) * 100);
}

// 处理补充库存
function handleRefillStock(productId) {
  console.log('处理补充库存:', productId);
  // 跳转到商品编辑页面
  router.push(`/main/seller/products?editId=${productId}`);
}

// 处理查看订单
function handleViewOrder(order) {
  console.log('处理查看订单:', order);
  // 跳转到订单详情页或打开订单详情对话框
  router.push(`/main/seller/seller-orders?orderId=${order.id}`);
}
</script>

<style scoped>
/* 状态图标样式 */
.status-icon {
  margin-right: 4px;
  vertical-align: middle;
  font-size: 12px;
}

/* 基本布局 */
.dashboard-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 0 16px 16px;
}

/* 欢迎区样式 */
.welcome-section {
  margin-bottom: 20px;
  padding: 20px;
  background: url('https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=1920&auto=format&fit=crop&h=200') center/cover no-repeat;
  color: white;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
}

.welcome-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(32, 95, 38, 0.6);
  z-index: 1;
}

.agri-page-title, .welcome-subtitle {
  position: relative;
  z-index: 2;
  color: white;
}

.agri-page-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
}

.welcome-subtitle {
  margin: 10px 0 0;
  font-size: 16px;
  opacity: 0.9;
}

/* 主布局 */
.dashboard-layout {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

/* 主内容区 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  min-width: 300px;
  max-width: 66%;
}

/* 侧边栏内容 */
.sidebar-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-width: 300px;
  flex: 0 0 30%;
}

/* 内容部分通用样式 */
.section-container, .widget-container {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.section-header, .widget-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-title, .widget-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #2e7d32;
}

.section-title .el-icon, .widget-title .el-icon {
  font-size: 18px;
}

.section-content, .widget-content {
  padding: 16px;
}

/* 产品网格 */
.product-grid {
  min-height: 240px;
}

.product-items {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 16px;
}

.product-item {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.product-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.product-image {
  height: 140px;
  position: relative;
}

.product-image .el-image {
  height: 100%;
  width: 100%;
}

.product-category {
  position: absolute;
  top: 8px;
  left: 8px;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.product-details {
  padding: 12px;
}

.product-name {
  margin: 0 0 8px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-farm {
  color: #666;
  font-size: 13px;
  margin-bottom: 8px;
}

.product-rating {
  margin-bottom: 8px;
}

.product-price {
  display: flex;
  align-items: baseline;
}

.price-value {
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.price-unit {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}

/* 种植布局 */
.planting-items {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.planting-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #f0f0f0;
  position: relative;
}

.planting-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.planting-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #67C23A, #95D475);
}

.planting-card-header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(to right, rgba(240, 249, 235, 0.6), rgba(245, 250, 246, 0.4));
}

.planting-avatar {
  margin-right: 16px;
  position: relative;
}

.planting-avatar::after {
  content: '';
  position: absolute;
  top: -2px;
  right: -2px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: #67C23A;
  border: 2px solid white;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.crop-avatar {
  background: linear-gradient(135deg, #67C23A, #95D475);
  color: white;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);
}

.planting-title {
  flex: 1;
  min-width: 0; /* 防止flex子项超出容器 */
}

.planting-title h3 {
  margin: 0 0 8px;
  font-weight: 600;
  font-size: 18px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.planting-card-body {
  padding: 16px;
}

.growth-progress-simple {
  margin-top: 16px;
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 8px;
  position: relative;
  overflow: hidden;
  border-left: 3px solid #67C23A;
}

.growth-progress-simple::after {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  width: 60px;
  height: 60px;
  background-image: radial-gradient(circle, rgba(103, 194, 58, 0.1) 0%, rgba(103, 194, 58, 0) 70%);
  border-radius: 50%;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.progress-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.progress-percentage {
  font-size: 18px;
  font-weight: bold;
  color: #67C23A;
}

.custom-progress :deep(.el-progress-bar__inner) {
  transition: all 0.8s ease;
  background-image: linear-gradient(90deg, #95D475, #67C23A);
}

.planting-info-table {
  margin-top: 16px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

@media (min-width: 768px) {
  .planting-info-table {
    grid-template-columns: repeat(4, 1fr);
  }
}

.info-row {
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
  border-left: 3px solid #67C23A;
}

.info-row:hover {
  background-color: #f0f7ff;
  transform: translateY(-2px);
  border-left-color: #409EFF;
}

.info-cell {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  color: #909399;
  font-size: 12px;
}

.info-cell .el-icon {
  margin-right: 4px;
  color: #67C23A;
  font-size: 16px;
}

.info-label {
  font-size: 12px;
  color: #909399;
}

.info-value-cell {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  word-break: break-all;
  overflow-wrap: break-word;
  line-height: 1.4;
}

/* 通知列表 */
.notification-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.notification-item {
  display: flex;
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 12px;
}

.notification-item.unread {
  background-color: #f0f9eb;
}

.notification-type {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
  flex-shrink: 0;
}

.notification-type.warning {
  background-color: #e6a23c;
}

.notification-type.system {
  background-color: #909399;
}

.notification-type.order {
  background-color: #409eff;
}

.notification-type.price {
  background-color: #67c23a;
}

.notification-details {
  flex: 1;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.notification-title {
  font-weight: 600;
  font-size: 14px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.notification-content {
  margin: 0;
  font-size: 13px;
  color: #606266;
}

/* 快捷操作 */
.shortcut-items {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.shortcut-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.shortcut-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  color: white;
  transition: transform 0.2s;
}

.shortcut-item:hover .shortcut-icon {
  transform: scale(1.1);
}

.shortcut-name {
  font-size: 13px;
  text-align: center;
}

/* 空状态 */
.empty-section, .empty-widget {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-widget {
  min-height: 120px;
}

/* 响应式布局 */
@media (max-width: 1280px) {
  .main-content {
    max-width: 60%;
  }
  
  .sidebar-content {
    flex: 0 0 35%;
  }
  
  .compact-card .low-stock-item {
    grid-template-columns: 150px 1fr auto;
  }
}

@media (max-width: 1024px) {
  .dashboard-layout {
    flex-direction: column;
  }
  
  .main-content, .sidebar-content {
    max-width: 100%;
    flex: 1 1 100%;
  }
  
  .sidebar-content {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  }
}

@media (max-width: 768px) {
  .product-items {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }
  
  .planting-items {
    grid-template-columns: 1fr;
  }
  
  .sidebar-content {
  display: flex;
  flex-direction: column;
  }
  
  .welcome-section .agri-page-title h2 {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .dashboard-container {
    padding: 0 8px 8px;
  }
  
  .welcome-section {
    padding: 16px;
  }
  
  .product-items {
    grid-template-columns: 1fr;
  }
  
  .shortcut-items {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .planting-items {
    grid-template-columns: 1fr;
  }
  
  .planting-info-table {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
  
  .planting-card-body {
    padding: 12px;
  }
  
  .info-row {
    padding: 8px;
  }
  
  .info-cell {
    font-size: 11px;
  }
  
  .info-cell .el-icon {
    font-size: 14px;
  }
  
  .info-value-cell {
  font-size: 12px;
}

  .growth-progress-simple {
    padding: 12px;
    margin-top: 12px;
  }
  
  .progress-title {
    font-size: 14px;
  }
  
  .progress-percentage {
    font-size: 16px;
  }
}

/* 卖家仪表盘样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  border-radius: 10px;
  padding: 20px;
  display: flex;
  color: white;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  height: 60px;
  width: 60px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-title {
  font-size: 14px;
  margin-bottom: 10px;
  opacity: 0.9;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 14px;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  padding: 2px 10px;
  display: inline-flex;
}

.stat-trend.up {
  color: #67C23A;
  background-color: rgba(103, 194, 58, 0.2);
}

.stat-trend.down {
  color: #F56C6C;
  background-color: rgba(245, 108, 108, 0.2);
}

.chart-container {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.sales-chart {
  height: 300px;
  width: 100%;
}

.chart-placeholder {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-mock {
  width: 100%;
  height: 200px;
  position: relative;
  overflow: hidden;
}

.chart-line, .chart-line-up {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100px;
  border-bottom: 2px dashed #eee;
}

.chart-line-up {
  height: 50px;
}

.chart-dot {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #409EFF;
  border-radius: 50%;
  bottom: 0;
  left: 5%;
}

.price-text {
  color: #F56C6C;
  font-weight: bold;
}

.low-stock-alert {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
}

.low-stock-products {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.low-stock-item {
  padding: 6px;
  margin-bottom: 4px;
  display: grid;
  grid-template-columns: 180px 1fr auto;
  align-items: center;
  gap: 8px;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 8px;
  width: auto;
}

.product-thumb {
  width: 40px;
  height: 40px;
}

.product-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-price {
  color: #F56C6C;
  font-size: 14px;
}

.stock-info {
  width: 100%;
  margin: 0;
}

.stock-text {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.customer-stats {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stats-row {
  display: flex;
  gap: 20px;
}

.customer-stat-card {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  flex: 1;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
}

.customer-stat-card:hover {
  transform: translateY(-5px);
}

.customer-stat-icon {
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  height: 50px;
  width: 50px;
  color: white;
}

.customer-stat-content {
  flex: 1;
}

.customer-stat-title {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  margin-bottom: 5px;
}

.customer-stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.customer-distribution {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.customer-distribution h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.distribution-chart {
  height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pie-chart-mock {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background-color: #eee;
  overflow: hidden;
}

.pie-slice1, .pie-slice2, .pie-slice3, .pie-slice4 {
  position: absolute;
  width: 150px;
  height: 150px;
  transform-origin: 50% 50%;
}

.pie-slice1 {
  background-color: #409EFF;
  clip-path: polygon(50% 50%, 100% 0%, 100% 100%);
}

.pie-slice2 {
  background-color: #67C23A;
  clip-path: polygon(50% 50%, 100% 100%, 0% 100%);
}

.pie-slice3 {
  background-color: #E6A23C;
  clip-path: polygon(50% 50%, 0% 100%, 0% 0%);
}

.pie-slice4 {
  background-color: #F56C6C;
  clip-path: polygon(50% 50%, 0% 0%, 50% 0%);
}

.pie-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: white;
}

@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .stats-cards, .stats-row {
    grid-template-columns: 1fr;
    flex-direction: column;
  }
  
  .product-info {
    width: 100%;
  }
  
  .low-stock-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .stock-info {
    width: 100%;
    margin: 10px 0;
  }
}

/* 添加紧凑卡片样式 */
.compact-card {
  max-height: 300px;
  overflow: hidden;
  width: 100%;
}

.compact-card .section-content {
  padding: 8px;
  max-height: 240px;
  overflow-y: auto;
}

.compact-card .empty-section {
  min-height: 120px;
}

.compact-card .el-table {
  font-size: 13px;
}

.compact-card .el-table th,
.compact-card .el-table td {
  padding: 6px 0;
}

.compact-card .low-stock-products {
  max-height: 280px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.compact-card .low-stock-item {
  padding: 8px;
  margin-bottom: 4px;
  display: grid;
  grid-template-columns: 200px 1fr auto;
  align-items: center;
  gap: 12px;
}

.compact-card .product-info {
  display: flex;
  align-items: center;
  gap: 10px;
  width: auto;
}

.compact-card .product-thumb {
  width: 50px;
  height: 50px;
}

.compact-card .stock-info {
  width: 100%;
  margin: 0;
}
</style> 